package com.binlog.core;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.binlog.config.BinLogDbProperty;
import com.binlog.config.BinLogDbPropertys;
import com.binlog.core.container.ClintContainer;
import com.binlog.core.listener.CommonEventListener;
import com.binlog.module.DatebaseInfo;
import com.binlog.module.TableColum;
import com.binlog.util.DruidDataSource;
import com.binlog.util.MysqlUtils;
import com.github.shyiko.mysql.binlog.BinaryLogClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Binlog listener starter
 *
 * @description: binlog监听启动类
 * @author: cyj
 * @date 2022 -05-13 15:39:36
 */
@Component
@Slf4j
public class BinlogSubscriptionStarter implements CommandLineRunner {


    @Autowired
    private BinLogDbPropertys binLogDbPropertys;

    private static ExecutorService EXECUTE;

    @Override
    public void run(String... args) {

        log.info("监听数据库配置信息：{}", JSON.toJSONString(binLogDbPropertys));


        EXECUTE = new ThreadPoolExecutor(binLogDbPropertys.getDatasource().size(), binLogDbPropertys.getDatasource().size(),
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("Client" + "-" + threadNumber.getAndIncrement());
                return thread;
            }
        }, new ThreadPoolExecutor.AbortPolicy());


        // 初始化数据源
        DruidDataSource.initDatesource(binLogDbPropertys);
        /**
         * binaryLogClient.connect 会马上阻塞，这里要多线程处理下
         */
        binLogDbPropertys.getDatasource().stream().forEach(this::processBinlogListener);
    }

    /**
     * 进行监听链接
     * @param binLogDbProperty
     */
    public void processBinlogListener(BinLogDbProperty binLogDbProperty) {
        EXECUTE.submit(() -> {
            // 获取table集合
            List<String> tables = MysqlUtils.getTableByStr(binLogDbProperty.getTable());
            if (CollectionUtil.isEmpty(tables)) {
                return;
            }
            // 取一下表结构
            Map<String, Map<String, TableColum>> schemaTable = new HashMap<>();
            tables.stream().forEach(table -> schemaTable.put(table, MysqlUtils.getColMap(binLogDbProperty, table)));

            // 备份库信息
            DatebaseInfo datebaseInfo = MysqlUtils.getDatebaseInfo(binLogDbProperty, binLogDbPropertys.getBackupsDatasource());

            // 注册监听
            log.info("开始 注册监听信息，注册DB：{}，注册表： {}, 结构信息：{}", binLogDbProperty.getSchema(), tables, JSON.toJSONString(schemaTable));
            try {
                int serverId = this.generalServiceId();
                log.info("serviceId:{}", serverId);
                BinaryLogClient binaryLogClient = new BinaryLogClient(
                        binLogDbProperty.getHost(),
                        binLogDbProperty.getPort(),
                        binLogDbProperty.getSchema(),
                        binLogDbProperty.getUsername(),
                        binLogDbProperty.getPassword());
                binaryLogClient.setServerId(serverId);
                binaryLogClient.registerEventListener(new CommonEventListener(schemaTable, binLogDbProperty, datebaseInfo));
                // 添加到容器并启动
                ClintContainer.addClient(binaryLogClient, binLogDbProperty);
            } catch (Exception e) {
                log.error("BinLog监听异常结束", e.getMessage(), e);
                System.exit(0);
            }
        });
    }

    /**
     * 获取serviceId
     * @return
     */
    private int generalServiceId() {
        Random random = new Random();
        return random.nextInt(10000) % (10000 - 1000 + 1) + 1000;
    }

    /**
     * 重新启动容器
     * @param serverId
     * @param positionId
     * @param positionFileName
     */
    @SneakyThrows
    public void restartClient(Long serverId, Long positionId, String positionFileName) {
        BinaryLogClient binaryLogClient = ClintContainer.BINARY_LOG_CLIENT_MAP.get(serverId);
        if (null == binaryLogClient) {
            return;
        }
        BinLogDbProperty binLogDbProperty = ClintContainer.BINARY_LOG_PROPERTY_MAP.get(serverId);
        BinaryLogClient binaryLogClientNew = new BinaryLogClient(
                binLogDbProperty.getHost(),
                binLogDbProperty.getPort(),
                binLogDbProperty.getSchema(),
                binLogDbProperty.getUsername(),
                binLogDbProperty.getPassword());

        int restartServerId = this.generalServiceId();
        log.info("restart serviceId:{}", serverId);
        binaryLogClientNew.setServerId(restartServerId);
        binaryLogClientNew.getEventListeners().stream().forEach(binaryLogClientNew::registerEventListener);
        binLogDbProperty.setBinlogPosition(positionId);
        binLogDbProperty.setBinlogFilename(positionFileName);

        ClintContainer.removeClient(serverId);
        // 添加到容器并启动
        ClintContainer.addClient(binaryLogClientNew, binLogDbProperty);
    }
}